# -*- coding: utf-8 -*-
import traceback
from qcloudsms_py.send_email import email_public
import datetime
from utils.backcode import ImportError
from app.project.common.project_sql import ProjectSql
from utils.logger import Md_Debug
from utils.db_utils import DbConn
from app.project.common.project_sql import ProjectSql
from utils.serialization import Serialization


class ProjectDB(object):
    """项目"""
    
    def __init__(self):
        self.db = DbConn()
        self.nowtime = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
    
    def get_all_project(self, body):
        """项目列表"""
        try:
            all_project = dict()
            # db = DbConn()
            project_name = body.get('project_name', None)
            page = body.get('page', None)
            size = body.get('size', None)
            
            # check parameter
            if not page:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "page is none"
            elif not size:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "size is none"
            else:
                SQL = ProjectSql.QUERY_PROJECT_LIST
                if project_name:
                    SQL = SQL + " WHERE project_name LIKE '%%%%%s%%%%' " % project_name
                
                SQL = SQL + ProjectSql.QUERY_PROJECT_LIST_END
                all_projects_list = self.db.fetch_all(SQL)
                paging_back = ProjectDB.paging(self, all_projects_list, page, size)
                code = ImportError.IMPORT_CODE_SUCCESS
                message = paging_back['data']
                all_project['total_page'] = paging_back['total_page']
                all_project['total_size'] = paging_back['total_size']
                all_project['page'] = paging_back['page']
                all_project['size'] = paging_back['size']
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        all_project['response_code'] = code
        all_project['response_msg'] = message
        return all_project
    
    def paging(self, data_list, page, size):
        """分页"""
        ret = {
            'page': page, 'size': size, 'total_page': 0, 'total_size': 0
        }
        total_size = len(data_list)
        if total_size % size == 0:
            total_page = total_size / size
        else:
            total_page = total_size / size + 1
        start_index = (page - 1) * size
        end_index = page * size
        ret['total_page'] = total_page
        ret['total_size'] = total_size
        ret['data'] = data_list[start_index: end_index]
        return ret
    
    def add_project(self, body):
        """
        添加项目
        :param body:
        :return:
        """
        try:
            ret = dict()
            # db = DbConn()
            project_name = body.get("project_name", None)
            user_id = body.get("user_id", None)
            
            # check parameter
            if not project_name:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "project_name is none"
            elif not user_id:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "user_id is none"
            else:
                param = [project_name, user_id, self.nowtime]
                self.db.commit(ProjectSql.ADD_PROJECT_SQL, param)
                code = ImportError.IMPORT_CODE_SUCCESS
                message = "success"
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        ret['response_code'] = code
        ret['response_msg'] = message
        return ret
    
    def get_all_task(self, body):
        """任务列表"""
        try:
            ret = dict()
            project_name = body.get("project_name", None)
            partner_id = body.get("partner_id", None)
            task_name = body.get("task_name", None)
            is_start = body.get("is_start", None)
            level = body.get("level", None)
            page = body.get('page', None)
            size = body.get('size', None)
            
            # check parameter
            if not page:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "page is none"
            elif not size:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "size is none"
            else:
                SQL = ProjectSql.ALL_TASK
                if project_name:
                    SQL = SQL + " AND project_name LIKE '%%%%%s%%%%' " % project_name
                if task_name:
                    SQL = SQL + " AND task_name LIKE '%%%%%s%%%%' " % task_name
                if partner_id:
                    SQL = SQL + " AND ui.id = '%s' " % partner_id
                if level:
                    SQL = SQL + " AND level = '%s' " % level
                if is_start:
                    SQL = SQL + " AND is_start = '%s' " % is_start
                SQL = SQL + ProjectSql.ALL_TASK_END
                task_data = self.db.fetch_all(SQL)
                paging_back = ProjectDB.paging(self, task_data, page, size)
                code = ImportError.IMPORT_CODE_SUCCESS
                message = paging_back['data']
                ret['total_page'] = paging_back['total_page']
                ret['total_size'] = paging_back['total_size']
                ret['page'] = paging_back['page']
                ret['size'] = paging_back['size']
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        ret['response_code'] = code
        ret['response_msg'] = message
        return ret
    
    def add_task(self, body):
        """添加任务"""
        try:
            ret = dict()
            task_name = body.get("task_name", None)
            project_id = body.get("project_id", None)
            journal = body.get("journal", None)
            user_id = body.get("user_id", None)
            plan_start_time = body.get("plan_start_time", None)
            plan_end_time = body.get("plan_end_time", None)
            partner_id = body.get("partner_id", None)
            
            # check parameter
            if not task_name:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "task_name is none"
            elif not project_id:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "project_id is none"
            elif not journal:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "journal is none"
            elif not user_id:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "user_id is none"
            elif not plan_start_time:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "plan_start_time is none"
            elif not plan_end_time:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "plan_end_time is none"
            elif not partner_id:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "partner_id is none"
            else:
                param = [task_name, project_id, journal, user_id, plan_start_time, plan_end_time, partner_id,
                         self.nowtime, 1]
                self.db.commit(ProjectSql.ADD_TASK, param)
                code = ImportError.IMPORT_CODE_SUCCESS
                message = "success"
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        ret['response_code'] = code
        ret['response_msg'] = message
        return ret
    
    def start_task(self, body):
        """开启任务"""
        try:
            ret = dict()
            task_id = body.get("task_id", None)
            # 0 :开启   1：结束
            oper_type = body.get("oper_type", None)
            
            # check paramete
            if not task_id:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "task_id is none"
            elif not oper_type:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "oper_type is none"
            else:
                if oper_type == "0":
                    param = [self.nowtime, 0, task_id]
                    self.db.commit(ProjectSql.START_TASK, param)
                    code = ImportError.IMPORT_CODE_SUCCESS
                    message = "success"
                elif oper_type == "1":
                    # 查询开始时间
                    param = [self.nowtime, 2, task_id]
                    self.db.commit(ProjectSql.END_TASK, param)
                    code = ImportError.IMPORT_CODE_SUCCESS
                    message = "success"
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        ret['response_code'] = code
        ret['response_msg'] = message
        return ret
    
    def date_split(self, startt, endt):
        """处理数据"""
        try:
            startt = str(startt)
            endt = str(endt)
            a = startt.split(' ')
            b = a[0].split('-')
            c = a[1].split(':')
            a1 = endt.split(' ')
            b1 = a1[0].split('-')
            c1 = a1[1].split(':')
            date1 = datetime.datetime(int(b[0]), int(b[1]), int(b[2]), int(c[0]), int(c[1]), int(c[2]))
            date2 = datetime.datetime(int(b1[0]), int(b1[1]), int(b1[2]), int(c1[0]), int(c1[1]), int(c1[2]))
            data = (date2 - date1).seconds
            hour = data / 3600
            minute = (data - hour * 3600) / 60
            second = (data - hour * 3600 - minute * 60)
            time = str(hour) + '时' + str(minute) + '分' + str(second) + '秒'
        except Exception as e:
            Md_Debug.error(traceback.format_exc(e))
        return time
    
    def all_field(self):
        """下拉列表"""
        try:
            ret = dict()
            project = self.db.fetch_all(ProjectSql.PROJECT)
            partner = self.db.fetch_all(ProjectSql.PARTNER)
            ret['code'] = ImportError.IMPORT_CODE_SUCCESS
            ret['project'] = project
            ret['partner'] = partner
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
            ret['code'] = code
            ret['message'] = message
        return ret
    
    def show_all_partner(self, body):
        """展示所有成员"""
        try:
            ret = dict()
            page = body.get("page", None)
            size = body.get("size", None)
            
            # check paramete
            if not page:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "page is none"
            elif not size:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "size is none"
            else:
                show_all_partner = self.db.fetch_all(ProjectSql.SHOW_ALL_PARTNER)
                paging_back = ProjectDB.paging(self, show_all_partner, page, size)
                code = ImportError.IMPORT_CODE_SUCCESS
                message = paging_back['data']
                ret['total_page'] = paging_back['total_page']
                ret['total_size'] = paging_back['total_size']
                ret['page'] = paging_back['page']
                ret['size'] = paging_back['size']
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        ret['response_code'] = code
        ret['response_msg'] = message
        return ret
    
    def add_partner(self, body):
        """添加成员"""
        try:
            ret = dict()
            partner_name = body.get("partner_name", None)
            work_number = body.get("work_number", None)
            
            # check paramete
            if not partner_name:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "partner_name is none"
            elif not work_number:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "work_number is none"
            else:
                param = [partner_name, work_number]
                self.db.commit(ProjectSql.ADD_PARTBER, param)
                code = ImportError.IMPORT_CODE_SUCCESS
                message = "success"
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        ret['response_code'] = code
        ret['response_msg'] = message
        return ret
    
    def add_journal(self, body):
        """记录日志"""
        try:
            ret = dict()
            work_progress = body.get("work_progress", None)
            user_id = body.get("user_id", None)
            task_id = body.get("task_id", None)
            coordination_work = body.get("coordination_work", None)
            experience = body.get("experience", None)
            
            # check paramete
            if not work_progress:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "work_progress is none"
            elif not user_id:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "user_id is none"
            elif not task_id:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "task_id is none"
            else:
                param = [work_progress, user_id, task_id, coordination_work, experience, self.nowtime]
                self.db.commit(ProjectSql.ADD_JOURNAL, param)
                code = ImportError.IMPORT_CODE_SUCCESS
                message = "success"
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        ret['response_code'] = code
        ret['response_msg'] = message
        return ret
    
    def all_journal(self, body):
        """日志列表"""
        try:
            ret = dict()
            start_time = body.get("start_time", None)
            end_time = body.get("end_time", None)
            page = body.get("page", None)
            size = body.get("size", None)
            user_id = body.get("user_id", None)
            param = []
            
            # check paramete
            if not page:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "page is none"
            elif not size:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "size is none"
            else:
                SQL = ProjectSql.ALL_JOURNAL
                if start_time and not end_time:
                    SQL = SQL + " AND journal.creat_time >= %s "
                    param.append(start_time)
                elif end_time and not start_time:
                    SQL = SQL + " AND journal.creat_time <= %s "
                    param.append(end_time)
                elif start_time and end_time:
                    SQL = SQL + " AND journal.creat_time BETWEEN %s AND %s  "
                    param.append(start_time)
                    param.append(end_time)
                
                if user_id:
                    SQL = SQL + " AND journal.user_id = %s "
                    param.append(user_id)
                SQL = SQL + ProjectSql.ALL_JOURNAL_END
                data = self.db.fetch_all(SQL, param)
                paging_back = ProjectDB.paging(self, data, page, size)
                code = ImportError.IMPORT_CODE_SUCCESS
                message = paging_back['data']
                ret['total_page'] = paging_back['total_page']
                ret['total_size'] = paging_back['total_size']
                ret['page'] = paging_back['page']
                ret['size'] = paging_back['size']
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        ret['response_code'] = code
        ret['response_msg'] = message
        return ret
    
    def send_message(self, body):
        """发送邮件"""
        try:
            ret = dict()
            content_param = dict()
            user_email = body.get("user_email", None)
            user_name = body.get("user_name", None)
            date = body.get("date", None)
            
            # check paramete
            if not user_email:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "user_email is none"
            elif not user_name:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "user_name is none"
            elif not date:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "date is none"
            else:
                content_param['user_email'] = user_email
                content_param['user_name'] = user_name
                date = str(date)
                date_year = (date.split(' ')[0]).split('-')[0]
                date_month = (date.split(' ')[0]).split('-')[1]
                date_day = (date.split(' ')[0]).split('-')[2]
                date_final = date_year + "年" + date_month + "月" + date_day + "日" + date.split(' ')[1]
                content_param['date'] = date_final
                if email_public(0, content_param):
                    code = ImportError.IMPORT_CODE_SUCCESS
                    message = "success"
                else:
                    code = ImportError.IMPORT_CODE_INVALID_OPE
                    message = "faile"
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        ret['response_code'] = code
        ret['response_msg'] = message
        return ret


class ProjectQueryDB(object):
    def __init__(self):
        self.serialization = Serialization()
    
    def project_list(self, body):
        """项目列表"""
        params = ['page', "size"]
        null_params = []
        sql = ProjectSql.PROJECT_LIST
        ret = self.serialization.query_list(body, params, null_params, sql)
        return ret
    
    def project_member_list(self, body):
        """项目团队列表"""
        params = ["page", "size"]
        null_params = []
        sql = ProjectSql.PROJECT_GROUP_LIST
        ret = self.serialization.query_list(body, params, null_params, sql)
        return ret
    
    def project_info(self, body):
        """项目信息"""
        params = ['id']
        null_params = []
        sql = ProjectSql.PROJECT_INFO
        ret = self.serialization.query_info(body, params, null_params, sql)
        return ret
    
    def project_member_info(self, body):
        """项目团队信息"""
        params = ["page", "size", "id"]
        null_params = ["page", "size"]
        sql = ProjectSql.PROJECT_GROUP_INFO
        ret = self.serialization.query_list(body, params, null_params, sql)
        return ret
    
    def project_leader_list(self, body):
        """可以作为领导的列表"""
        params = ["page", "size", "session_department"]
        null_params = ["page", "size"]
        sql = ProjectSql.PROJECT_GROUP_LEADER_LIST
        ret = self.serialization.query_list(body, params, null_params, sql)
        return ret
    
    def project_info_person(self, body):
        # 查看自己所在的项目
        params = ["page", "size", "session_user_id", "session_company_post"]
        null_params = ["page", "size"]
        sql = ProjectSql.PROJECT_INFO_PERSON
        ret = self.serialization.query_list(body, params, null_params, sql)
        return ret
    
    def project_info_person_all(self, body):
        # 查看自己所在的项目
        params = ["page", "size", "session_user_id", "session_company_post"]
        null_params = ["page", "size"]
        sql = ProjectSql.PROJECT_INFO_PERSON_ALL
        ret = self.serialization.query_list(body, params, null_params, sql)
        return ret
    
    # def project_info_person_all(self,body):
    #     # 查看所有进行的项目
    #     params = ["page","size","session_user_id"]
    #     null_params = ["page","size"]
    #     sql = ProjectSql.PROJECT_INFO_PERSON_ALL
    #     ret = self.serialization.query_list(body, params, null_params, sql)
    #     return ret
    
    def project_empty_person(self, body):
        """查看没有项目的用户"""
        params = ["page", "size", ]
        null_params = ["page", "size"]
        sql = ProjectSql.PROJECT_EMPTY_PERSON
        ret = self.serialization.query_list(body, params, null_params, sql)
        return ret
    
    def project_group_list_info(self, body):
        params = ["page", "size", "session_user_id", "session_company_post"]
        null_params = ["page", "size"]
        sql = ProjectSql.PROJECT_GROUP_LIST_PERSON
        ret = self.serialization.query_list(body, params, null_params, sql)
        return ret
    
    def project_search(self, body):
        params = ['page', 'size', "search_content", "search_content", "search_content"]
        null_params = ["page", "size"]
        sql = ProjectSql.PROJECT_SEARCH
        ret = self.serialization.query_list(body, params, null_params, sql)
        return ret


if __name__ == '__main__':
    import datetime, time
